import SockJS from  'sockjs-client';
import Stomp from 'stompjs';
import api from "./api.js"
// import util from "./util.js"

let stompClient = null;
/**
 * 连接后台ws
 */
function connectWebSocket(wsTopics) {
	// 建立连接对象
	let socket = new SockJS(api.completeServerHost(api.WS_ENTRY_POINT));
	// 获取STOMP子协议的客户端对象
	stompClient = Stomp.over(socket);
	// 定义客户端的认证信息,按需求配置
	let headers = {
		Authorization: ""
	};
	// 向服务器发起websocket连接
	stompClient.connect(
		headers,
		res => {
			console.log("websocket连接成功：", res)
			//连接成功 订阅系统信息主题消息
			if (wsTopics) {
				wsTopics.forEach( topic => {
					stompClient.subscribe(topic.key, msg => {
						console.log("获得websocket消息通知....", msg)
						// util.playSound(topic.key, msg.body);
						topic.action.apply(this);
					})
				})
			}
		},
		err => {
			// 连接发生错误时的处理函数，支持断开重连机制
			console.log("websocket连接失败：", err);
			stompClient = null;
			//10秒后重试
			setTimeout(connectWebSocket, 3000);
		}
	);
}

/**
 * 断开连接
 *
 */
function disconnectWebSocket() {
	if (stompClient) {
		stompClient.disconnect();
		stompClient = null;
	}
}


export default {
    connectWebSocket,
    disconnectWebSocket,
}